
import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList, Animated, View, Image, TouchableOpacity, Alert
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ApprovalCpt } from '../_components/ApprovalCpt';
import MethodUtil from '../../../utils/MethodUtil';
import ToastUtil from '../../../utils/toast';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
const scale = GLOBAL.SCALE;
const correct = require('../../../imgs/global/correct.png')
const titleImgObj = require('../../../imgs/global/down.png');


export class WholePackList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '成交申请列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		let { bidPackageId, periodNum, bizModel, winRule, salesType } = props.navigation.state.params || {};
		this.state = {
			status: 'data',
			refreshIcon: false,
			listData: [],
			allText: '',
			showRejectModal: false
		}
		this.pageParams = {
			bidPackageId
		}
		this.applyParams = {
			applyInfo: {
				applyType: '',
				bizModel: 'Z',
				winRule: 'ALL',
				salesType,
				periodNum,
				bidPackageId
			},
			itemList: []
		}
		this.bizModel = bizModel
		this.winRule = winRule
		this.salesType = salesType
		this.selectData = {};
	}

	async componentWillMount() {
		await this.initPage();
	}
	//初始化数据
	initPage = async () => {
		this.setState({
			status: 'loading',
			refreshIcon: true
		})
		let res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_LIST), this.pageParams);
		if (res) {
			this.setState({
				listData: res,
				status: res ? 'data' : 'empty',
				refreshIcon: false,
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}
	changeCheck = (index) => {
		let { listData, isAll } = this.state;
		listData[index].select = !listData[index].select
		listData.map((item, i) => {
			if (listData[index].select === false && i > index) {
				item.select = false
			}
			else if (listData[index].select === true && i < index) {
				item.select = true
			}
			if (!item.select) {
				isAll = false
			}
			else {
				isAll = true
			}
		})
		this.setState({
			listData, isAll
		}, () => {
			this.bottomText()
		});
	}
	//全选方法
	_selectAll = (isAll) => {
		let { listData } = this.state;
		listData.map((item) => {
			item.select = isAll
		})
		this.setState({
			listData,
			isAll
		}, () => {
			this.bottomText()
		});
	}

	bottomText = () => {
		let { listData } = this.state;
		let num = 0, qty = 0, allText;
		listData.map((item) => {
			if (item.select) {
				num++;
				qty += item.purchaseQty
			}
		})
		if (num == 0) {
			allText = ''
		}
		else {
			allText = '全选 ' + num + '条,' + qty + '吨'
		}

		this.setState({
			allText
		})
	}

	_refused = () => {
		this.applyParams.applyInfo.applyType = 'REJECT'
		this.setState({
			showRejectModal: true
		})
	}
	_agree = () => {
		this.applyParams.applyInfo.applyType = 'ACCEPT'
		this.setState({
			showRejectModal: true
		})
	}
	//成交
	approve = async () => {
		let { listData } = this.state;
		this.applyParams.itemList = []
		this.setState({
			showRejectModal: false,
		})
		listData.map((item) => {
			if (item.select == true) {
				this.applyParams.itemList.push(
					{ bidId: item.bidId }
				)
			}
		})
		if (this.applyParams.itemList.length === 0) {
			ToastUtil.showWarning('请选择成交对象');
			return
		}
		let res = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_APPLY), this.applyParams);
		if (res) {
			this.setState({
				status: 'data',
			}, () => {
				ToastUtil.showSuccess(this.applyParams.applyInfo.applyType === 'ACCEPT' ? '成交成功' : '拒绝成功').then(() => {
					this._goBack();
				})
			})
		}
	}
	_goBack = () => {
		this.props.navigation.navigate('ClinchRecord', {
			bidPackageId: this.pageParams.bidPackageId, bizModel: this.bizModel, winRule: this.winRule, salesType: this.salesType
		})
	}
	_renderListItem = (data, index) => {
		return (
			<View style={styles.itemBox}>
				<View style={styles.itemTop}>
					<TouchableOpacity style={styles.itemTopLeft} onPress={() => this.changeCheck(index)}>
						<View style={styles.checkBox}>
							<View style={styles.lockView}>
								{
									data.select ? <Image style={styles.lockImage} source={correct} /> : null
								}
							</View>
						</View>
						<Text style={{ fontSize: 12 * scale }}>{data.companyName}</Text>
					</TouchableOpacity>
					<TouchableOpacity onPress={() => {
						this.props.navigation.navigate('OfferDetail', {
							headTitle: '客户报盘明细',
							bidPackageId: this.pageParams.bidPackageId,
							bidId: data.bidId,
							type: 'package',
							totalPrice: data.totalPrice,
							purchaseQty: data.purchaseQty
						})
					}}
						style={{ width: 50 * scale, alignItems: 'flex-end', paddingVertical: 10 * scale, paddingRight: 10 * scale }}
					>
						<Image source={titleImgObj} style={styles.imgStyle} />
					</TouchableOpacity>
				</View>
				<View style={styles.itemBottom}>
					<Text style={{ fontSize: 12 * scale }}>成交总额：
						<Text style={{ fontSize: 12 * scale, fontWeight: '600' }}>
							¥{MethodUtil.toThousands(data.totalPrice || 0, 2)}
						</Text>
					</Text>
					<Text style={{ fontSize: 12 * scale }}>成交总量：
						<Text style={{ fontSize: 12 * scale, fontWeight: '600' }}>
							{data.purchaseQty}
						</Text>
						吨
					</Text>
				</View>
			</View>
		)
	}
	render() {
		let { listData, refreshIcon, status, isAll, allText, showRejectModal } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.body}>
					<FlatList
						data={listData}
						renderItem={({ item, index }) => this._renderListItem(item, index)}
						refreshing={refreshIcon}
						onRefresh={() => { this.initPage() }}
					/>
					<ApprovalCpt
						data={{ isAll, allText }}
						method={{ selectAll: this._selectAll, refused: this._refused, agree: this._agree }}
					/>
				</View>
				{status !== 'data' ?
					<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
						<PageStatusIndex status={status} onErrorPress={() => { this.initPage() }} />
					</View> : null
				}
				<RefuseModal
					titleText={this.applyParams.applyInfo.applyType == 'ACCEPT' ? '成交理由' : '拒绝理由'}
					placeholderText={this.applyParams.applyInfo.applyType == 'ACCEPT' ? '请输入成交原因' : '请输入驳回原因'}
					visible={showRejectModal}
					btnPress={(text) => {
						this.applyParams.applyInfo.comments = text;
						this.approve();
					}}
					bgPress={() => {
						this.setState({
							showRejectModal: false,
						});
					}} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	body: {
		flex: 1,
		backgroundColor: '#E8ECF5',
	},
	itemBox: {
		marginTop: 20 * scale,
		backgroundColor: '#fff',
		borderRadius: 6 * scale,
		marginHorizontal: 20 * scale
	},
	itemTop: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale
	},
	itemTopLeft: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingVertical: 10 * scale,
	},
	lockView: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		height: 12 * scale,
		width: 12 * scale,
		borderWidth: 1 * scale,
		borderColor: style.color.themeColor,
		marginRight: 10 * scale,
		marginLeft: 10 * scale
	},
	lockImage: {
		tintColor: style.color.themeColor,
		width: 8 * scale,
		height: 8 * scale,
		marginLeft: 1 * scale
	},
	imgStyle: {
		tintColor: '#000',
		width: 10 * scale,
		height: 6 * scale,
		transform: [{ rotate: '-90deg' }]
	},
	itemBottom: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		paddingVertical: 12 * scale,
		paddingHorizontal: 10 * scale,
	}
})